import "./style.scss";
import addPng from "@assets/statement/add.png";
import HttpUtils from "@page/common/utils/HttpUtils";
import Cascader from "@ui/RJMart/cascader";
import Input from "@ui/RJMart/input";
import Form from "@ui/RJMart/form";
import Icon from "@ui/RJMart/icons";
import City from "@page/common/utils/city";
import REST from "@module/Rest";
import Button from "@ui/RJMart/button";
import { Select, Option } from "@ui/RJMart/select";
import message from "@ui/RJMart/message";
import ToastUtils from "@page/common/utils/ToastUtils";
import CookieUtils from "pages/ruijing/common/utils/CookieUtils";
import SubjectInfo from "pages/ruijing/Statements/components/SubjectInfo";
import ZenModal from "@root/components/zenUi/ZenModal/ZenModal";
import AddDeptForm from "pages/ruijing/Statements/components/AddDept";


// import AddAddressModal from "../addAddressModal";

class AddressItem extends React.Component {
    constructor(props) {
        super(props);
        console.log("AddressItem",props)
        this.state = {
            isShowModal: false,
            addressInfo: {
                consignee: "",
                mobile: "",
                telephone: "",
                city: [],
                address: "",
                label:[],
                labelRemark:""
            },
            hasLabel:false,
            labelList:""
        };
    }

    componentDidMount() {
        if(this.state.labelList==""){
            this.getLabelList()
        }
    }

    componentWillReceiveProps(nextProps) {
        console.log(nextProps);
    }

    //设为默认
    setDefaulAddress(id, index, list) {
        let params = {
            id: id
        };
        HttpUtils.setAsDefault(params)
            .then(res => {
                console.log(res);
                this.props.setDefaul(index, list);
            })
            .catch(err => {
                console.log(err);
            });
    }

    //获取地址详情

    getAddressInfo(id) {
        let url = `/store/api/user/deliveryAddress/GetDeliveryAddressDetail`;
        ToastUtils.loading();

        REST.post(url, { id }).then(
            data => {
                if ((data.message = "success")) {
                    ToastUtils.hide();
                    let copyData = data;
                    copyData.city = [data.province, data.city, data.district];
                    copyData.labelRemark = data.remark;
                    this.setState(
                        {
                            addressInfo: copyData
                        },
                        () => {
                            this.modalCb(true);
                        }
                    );
                }
            },
            error => {
                ToastUtils.hide();
            }
        );
    }

    //获取收货标签列表
    getLabelList = () =>{
        let inputData = {
            orgId:CookieUtils.getCookie("orgId"),
            rankType:2
        }
        let url = "/store/api/hms/delivery/address/label/list"
        REST.post(url,inputData).then(
            data => {
                if (data.message == "success"||data.code=="200") {
                    console.log("getLabelList",data);
                    let labels =[];
                    data.data.map((item,index) =>{
                        labels.push(item.labelName)
                    })
                    console.log("getLabelList",this.props);
                    if(labels.length>0){
                        this.props.updateStateLabel()
                    }
                    this.setState({
                        labelList:labels,
                        hasLabel:labels.length>0?true:false
                    })
                }else{
                    ZenUI.ST(data.message, 2);
                }
            },
            error => {}
        );
    }

    //切换地址
    selectAddress = (index,list) =>{
        let needLabel = false;
        let targetId = "";
        list.forEach((v, k) => {
            if(index == k){
                if(this.state.hasLabel&&v.label==""){
                    needLabel =true;
                    targetId = v.id;
                }
            }
        });
        console.log("needLabel",needLabel,list,this.state.hasLabel,targetId);
        if(needLabel){
            this.showLabelModal(targetId)
        }else{
            this.props.selectAddress(index,list)
        }
    }

    showLabelModal = (targetId) =>{
        let showAddress = this;
        function editLabel() {
            showAddress.getAddressInfo(targetId);
            closeModal();
        }
        function closeModal(value) {
            console.log("run closeModal", value);
            modal.hide();
        }

        function Content(props) {
            console.log("props",props);
            props.item.editAddress = editLabel;
            return (
                <div>
                    <div className="zen_t-c zen_m-t-50 zen_m-b-50">
                        该地址需升级后才可使用，请编辑升级该地址
                    </div>
                    <div className="zen_t-c">
                        <button type="submit" onClick={props.item.editAddress} className={"h-button-primary h-modal-conBtn h-button-button"}>
                            编辑
                        </button>
                        <div onClick={props.item.close} className="h-button-button h-button-sub h-modal-canBtn">
                            取消
                        </div>
                    </div>
                </div>
            );
        }
        let options = {
            header: "提示",
            // footer: "test footer",
            content: Content,
            size: "sm",
            close: closeModal,
            hideFooter:true
        };
        let modal = ZenModal.loadModal(options);
        modal.show();
    }

    //open address modal
    addAddress = () => {
        this.setState({ isShowModal: true });
    };

    //open address modal
    updateSelect = () => {
        console.log("updateSelect",this.state.hasLabel);
        this.setState({ hasLabel: true });
    };

    // close address modal cb
    modalCb = (isShow, type) => {
        this.setState({
            isShowModal: isShow
        });
        if (type == "update") {
            this.props.updateAddress();
        }
    };
    renderItem() {
        const { isSelect, isShowAdd, list } = this.props;
        console.log("renderItem",this.props,this.state);

        if (isShowAdd) {
            return (
                <div
                    onClick={this.addAddress}
                    className={Uts.sc(['rj_address_item-wp',isSelect ? "rj_select-on" : "rj_select-off"])}
                >
                    <div className="rj-l-add-wp">
                        <img src={addPng} alt="" />
                        <p>添加新地址</p>
                    </div>
                </div>
            );
        } else {
            return (
                list &&
                list.map((val, index) => {
                    return (
                        <div
                            key={index}
                            className={Uts.sc(['rj_address_item-wp',val.select ? "rj_select-on" : "rj_select-off",list.length>=7?'zen_m-r-11':'zen_m-r-12'])}

                            onClick={this.selectAddress.bind(
                                this,
                                index,
                                list
                            )}
                        >
                            <div className="rj_address_item-top">
                                <span className="rj_l-person-name">
                                    {val.consignee}
                                </span>
                                <span className="rj_l-init-address">
                                    {val.default ? "默认地址" : ""}
                                </span>
                            </div>
                            <div className="rj_address_item-center">
                                {val.deliveryAdress}
                            </div>
                            <div className="rj_address_item-bottom">
                                <span className="rj_l-person-name">
                                    {val.mobile||val.telephone}
                                </span>
                            </div>
                            <div className="rj_address-btn">
                                <span
                                    className="rj_l-modify"
                                    onClick={this.getAddressInfo.bind(
                                        this,
                                        val.id
                                    )}
                                >
                                    修改
                                </span>
                                <span
                                    className="rj_l-setInit"
                                    onClick={this.setDefaulAddress.bind(
                                        this,
                                        val.id,
                                        index,
                                        list
                                    )}
                                >
                                    {val.default ? "" : "设为默认"}
                                </span>
                            </div>
                        </div>
                    );
                })
            );
        }
    }

    render() {
        const { isShowModal, addressInfo } = this.state;
        console.log("renderAddressItem",this.props,this.state);
        return (
            <div>
                {this.renderItem()}
                {isShowModal && (
                    <AddressModal
                        isShow={isShowModal}
                        info={addressInfo}
                        modalCb={this.modalCb}
                        isShowLabel={this.state.hasLabel}
                        labelList={this.state.labelList}
                    />
                )}
            </div>
        );
    }
}

class AddressModal extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            cityList: [],
            consignee: "",
            telephone: "",
            address: "",
            mobile: "",
            consigneeState: {
                status: "success",
                message: ""
            },
            addressState: {
                status: "success",
                message: ""
            },
            telephoneState: {
                status: "success",
                message: ""
            },
            mobileState: {
                status: "success",
                message: ""
            },
            cityNum: 99,
            selectSchool: [], //中大校区
            remarkState: {
                status: "success",
                message: ""
            },
            remark: "",
            isShowLabel:props.isShowLabel,
            labelList:props.labelList,
            selectLabel:[],
            labelRemark:"",
            isShowRemark:false,
            labelState:{
                status: "success",
                message: ""
            }
        };
        this.cityList = City.initCity() || [];
        this.orgId = Uts.getCookie("orgId");
    }

    componentDidMount() {
        //this.getLabelList();
        console.log("AddressModalDidMount",this.props,this.state)
        if (this.props.info) {
            //修改地址

            this.setState({
                cityList: this.props.info.city,
                consignee: this.props.info.consignee,
                telephone: this.props.info.telephone,
                address: this.props.info.address,
                mobile: this.props.info.mobile,
                selectLabel: [this.props.info.label],
                labelRemark:this.props.info.remark,
                isShowRemark:this.props.info.label=="其他"?true:false
            });
            if (this.orgId == "3") {
                let fIndex = this.props.info.address.lastIndexOf("-");
                let lIndex =
                    this.props.info.address.lastIndexOf("（") > -1
                        ? this.props.info.address.lastIndexOf("（")
                        : this.props.info.address.length;
                let rIndex =
                    this.props.info.address.lastIndexOf("）") > -1
                        ? this.props.info.address.lastIndexOf("）")
                        : this.props.info.address.length;
                let schoolList=[
                    "南校园",
                    "北校园",
                    "东校园",
                    "珠海校区",
                    "附属医院",
                    "其他"
                ];
                let selectSchool = schoolList.indexOf(this.props.info.address.substring(fIndex + 1, lIndex))==-1?[]:[this.props.info.address.substring(fIndex + 1, lIndex)]
                this.setState({
                    address: this.props.info.address.substring(0, fIndex),
                    selectSchool: selectSchool,
                    remark: this.props.info.address.substring(
                        lIndex ,
                        rIndex
                    )
                });
            }
        }
    }

    componentWillReceiveProps(nextProps) {
        console.log(nextProps);
    }

    //
    onChange = value => {
        this.setState({
            cityList: value
        });
    };

    handleClick = (e, isShow) => {
        if (e.target && e.target.className !== "rj_l-modal-bg") {
            return;
        }
        isShow = false;
        this.props.modalCb(isShow);
    };

    closeModal = () => {
        ToastUtils.hide();
        this.props.modalCb(false);
    };

    checkData(data) {
        if (!data.consignee) {
            this.setState({
                consigneeState: {
                    status: "error",
                    message: "请输入收货人"
                }
            });
            return false;
        } else {
            this.setState({
                consigneeState: {
                    status: "success",
                    message: ""
                }
            });
        }
        if (!data.province) {
            this.setState({
                cityNum: 0
            });
            return false;
        }
        if (!data.city) {
            this.setState({
                cityNum: 1
            });
            return false;
        }
        if (!data.district) {
            this.setState({
                cityNum: 2
            });
            return false;
        } else {
            this.setState({
                cityNum: 99
            });
        }
        if (this.state.isShowLabel&&(data.label==undefined||data.label.length<=0||data.label==null)){
            this.setState({
                labelState: {
                    status: "error",
                    message: "请选择地址标签"
                }
            });
            return false;
        }else if (data.label=="其他"&&!data.remark) {
            this.setState({
                labelState: {
                    status: "error",
                    message: "当选择其他标签时，必须填写备注原因"
                }
            });
            return false;
        }else if (data.label=="其他"&&data.remark.length>200) {
            this.setState({
                labelState: {
                    status: "error",
                    message: "备注原因最多不能超过200字"
                }
            });
            return false;
        } else {
            this.setState({
                labelState: {
                    status: "success",
                    message: ""
                }
            });
        }

        if (this.orgId == "3") {
            if (!this.state.selectSchool || !this.state.selectSchool[0]) {
                this.setState({
                    cityNum: 3
                });
                return false;
            } else {
                this.setState({
                    cityNum: 99
                });
            }
        }

        if (!data.address) {
            this.setState({
                addressState: {
                    status: "error",
                    message: "请输入详细地址"
                }
            });
            return false;
        } else {
            this.setState({
                addressState: {
                    status: "success",
                    message: ""
                }
            });
        }

        if (
            data.mobile &&
            !/^1[3|4|5|6|7|8|9][0-9]{9}$/.test(data.mobile)
        ) {
            this.setState({
                mobileState: {
                    status: "error",
                    message: "手机号格式有误"
                }
            });
            return false;
        } else {
            this.setState({
                mobileState: {
                    status: "success",
                    message: ""
                }
            });
        }

        if (
            data.telephone &&
            !/^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(data.telephone)
        ) {
            this.setState({
                telephoneState: {
                    status: "error",
                    message: "固定电话格式有误"
                }
            });
            return false;
        } else {
            this.setState({
                telephoneState: {
                    status: "success",
                    message: ""
                }
            });
        }

        if(['14'].indexOf(this.orgId)>-1) {
            if (!data.mobile&&!data.telephone) {
                this.setState({
                    telephoneState: {
                        status: "error",
                        message: "请选择填写手机号或固定电话"
                    }
                });
                return false;
            } else {
                this.setState({
                    telephoneState: {
                        status: "success",
                        message: ""
                    }
                });
            }

        } else {
            if (!/^1[3|4|5|6|7|8|9][0-9]{9}$/.test(data.mobile)) {
                this.setState({
                    mobileState: {
                        status: "error",
                        message: "手机号格式有误"
                    }
                });
                return false;
            } else {
                this.setState({
                    mobileState: {
                        status: "success",
                        message: ""
                    }
                });
            }
        }

        if (this.orgId == "3" && this.state.selectSchool.indexOf("其他") > -1) {
            if (!this.state.remark) {
                this.setState({
                    remarkState: {
                        status: "error",
                        message: "校区选择其他时，此项必填"
                    }
                });
                return false;
            } else {
                this.setState({
                    remarkState: {
                        status: "success",
                        message: ""
                    }
                });
            }
        }

        return true;
    }

    //修改地址

    updateDeliveryAddress(info) {
        let url = `/store/api/user/deliveryAddress/AddDeliveryAddress`;
        let { consignee, mobile, telephone, address, cityList,selectLabel,labelRemark } = this.state;
        let _params = {
            consignee,
            mobile,
            telephone,
            province: cityList[0],
            city: cityList[1],
            district: cityList[2],
            address
        };
        if(this.state.isShowLabel){
            _params.label = selectLabel[0];
            if(selectLabel[0]=="其他"){
                _params.remark = labelRemark;
            }
        }
        //中大个性化
        ToastUtils.loading();
        console.log("params",_params);
        if (this.checkData(_params)) {
            if (this.orgId == "3") {
                this.props.info.address.lastIndexOf("（") > -1
                // this.state.remark= this.state.remark.replace(/[（|）|-]/g,'');
                this.state.remark =this.state.remark.replace(/（/g,'(').replace(/）/g,')').replace(/-/g,'——');
                _params.address = _params.address.replace(/-/g,'——').replace(/（/g,'(').replace(/）/g,')');;
                _params.address = this.state.remark
                    ? `${_params.address}-${this.state.selectSchool[0]}（${
                          this.state.remark
                      }）`
                    : `${_params.address}-${this.state.selectSchool[0]}`;
            }
            if (this.props.info && this.props.info.id) {
                _params.id = this.props.info.id;
                url = `/store/api/user/deliveryAddress/UpdateDeliveryAddress`;
            }
            REST.post(url, _params).then(
                data => {
                    ToastUtils.hide();
                    if(this.orgId=='3'&&data.code=='0001'){
                        message.warn({ text: data.message || "", duration:3000 });
                    } else{
                        if ((data.message = "success")) {
                            this.props.modalCb(false, "update");
                        }
                    }
                    
                },
                error => {
                    ToastUtils.hide();
                }
            );
        }
    }

    handleChange(type, event) {
        const { value } = event.target;
        this.setState({
            [type]: value
        });
    }

    changeCampus = result => {
        this.setState({
            selectSchool: result
        });
        console.log(result);
    };

    changeLabel = result => {
        this.setState({
            selectLabel: result,
            isShowRemark:result[0] == "其他"?true:false,
            labelRemark:""
        });
        console.log(result);
    };

    render() {
        const { info, isShow } = this.props;
        console.log("renderAddressModal",this.props,this.state)
        const {
            consigneeState,
            cityList,
            cityNum,
            addressState,
            mobileState,
            telephoneState,
            selectSchool,
            selectLabel,
            remarkState,
            labelList,
            labelRemark,
            labelState,
            isShowRemark
        } = this.state;
        let placeholderList = ["省份", "地级市", "市、县级市"];
        let oddressInfo = info.address;
        let remark = "";
        if (this.orgId == "3") {
            placeholderList.push("校区");
            let fIndex = this.props.info.address.lastIndexOf("-");
            let lIndex =
                this.props.info.address.lastIndexOf("（") > -1
                    ? this.props.info.address.lastIndexOf("（")
                    : this.props.info.address.length;
            let rIndex =
                this.props.info.address.lastIndexOf("）") > -1
                    ? this.props.info.address.lastIndexOf("）")
                    : this.props.info.address.length;
            oddressInfo = this.props.info.address.substring(0, fIndex);
            remark = this.props.info.address.substring(lIndex + 1, rIndex);
        }
        return (
            <div>
                <div
                    className="rj_l-modal-bg"
                    onClick={(e, isShow) => this.handleClick(e, isShow)}
                />
                <div
                    className={Uts.sc([
                        "rj_l-add-modal-wp",
                        this.orgId == "3" ? "rj_zsdx" : ""
                    ])}
                >
                    <div className="rj_modal-tittle">
                        <span>新增地址</span>
                        <span className="rj_l-close" onClick={this.closeModal}>
                            <Icon
                                type="close"
                                width={17.52}
                                height={17.52}
                                verticalAlign="top"
                                color="#969696"
                            />
                        </span>
                    </div>
                    <div className="rj_l-form-wp">
                        <div className="zen_ps-re">
                            <span className={Uts.sc(['zen_fs-16 zen_f-left zen_ps-ab zen_t-10 zen_FF0000',this.orgId=='3'?'zen_l-33':'zen_l-20'])}>
                                *
                            </span>
                            <Form.Item
                                label="收货人"
                                message={consigneeState.message}
                                validateStatus={consigneeState.status}
                            >
                                <Input
                                    defaultValue={info.consignee}
                                    placeholder="请输入收货人"
                                    clearable
                                    error={
                                        consigneeState.status == "success"
                                            ? false
                                            : true
                                    }
                                    onChange={this.handleChange.bind(
                                        this,
                                        "consignee"
                                    )}
                                    onClearChange={this.handleChange.bind(
                                        this,
                                        "consignee"
                                    )}
                                />
                            </Form.Item>
                        </div>

                        <div className="h-form-item-wrapper rj_l-city-wp">
                            <span className={Uts.sc(['zen_fs-16 zen_f-left zen_ps-ab zen_t-10 zen_FF0000',this.orgId=='3'?'zen_l-33':'zen_l-20'])}>*</span>
                            <span className="rj_l-tittle">所属地区</span>
                            <Cascader
                                depth={3}
                                separate={true}
                                options={this.cityList}
                                onChange={this.onChange.bind(this)}
                                placeholder={placeholderList}
                                value={cityList}
                            />
                            {this.orgId == "3" && (
                                <div className="rj_zsdx-item">
                                    <Select
                                        selection={selectSchool}
                                        onChange={this.changeCampus}
                                        placeholder="校区"
                                    >
                                        {[
                                            "南校园",
                                            "北校园",
                                            "东校园",
                                            "珠海校区",
                                            "附属医院",
                                            "其他"
                                        ].map((val, index) => {
                                            return (
                                                <Option key={index} value={val}>
                                                    {val}
                                                </Option>
                                            );
                                        })}
                                    </Select>
                                </div>
                            )}
                            {cityNum <= 3 && (
                                <div className="rj_check-select">{`请选择${
                                    placeholderList[cityNum]
                                }`}</div>
                            )}
                        </div>
                        <div className={this.state.isShowLabel?"zen_ps-re":"zen_hide"}>
                            <span className={Uts.sc(['zen_fs-16 zen_f-left zen_ps-ab zen_t-10 zen_FF0000',this.orgId=='3'?'zen_l-33':'zen_l-20'])}>
                                *
                            </span>
                            <Form.Item
                                label="地址标签"
                                message={labelState.message}
                                validateStatus={labelState.status}
                            >
                                <Select
                                    selection={selectLabel}
                                    onChange={this.changeLabel}
                                    placeholder="请选择地址标签"
                                    style={{width:"40%",verticalAlign:"middle",float:"left",textAlign:"left"}}
                                >
                                    {labelList.map((val, index) => {
                                        return (
                                            <Option key={index} value={val}>
                                                {val}
                                            </Option>
                                        );
                                    })}
                                </Select>
                                {isShowRemark?<Input
                                    placeholder="请说明配送到该地址的原因"
                                    defaultValue={info.labelRemark}
                                    style={{width:"60%",display:"inline-block"}}
                                    onChange={this.handleChange.bind(
                                        this,
                                        "labelRemark"
                                    )}
                                    onClearChange={this.handleChange.bind(
                                        this,
                                        "labelRemark"
                                    )}
                                />:""}
                            </Form.Item>
                        </div>
                        <div className="zen_ps-re">
                            <span className={Uts.sc(['zen_fs-16 zen_f-left zen_ps-ab zen_t-10 zen_FF0000',this.orgId=='3'?'zen_l-33':'zen_l-20'])}>
                                *
                            </span>
                            <Form.Item
                                label="详细地址"
                                message={addressState.message}
                                validateStatus={addressState.status}
                            >
                                <Input
                                    placeholder="请输入详细地址"
                                    defaultValue={oddressInfo}
                                    clearable
                                    error={
                                        addressState.status == "success"
                                            ? false
                                            : true
                                    }
                                    onChange={this.handleChange.bind(
                                        this,
                                        "address"
                                    )}
                                    onClearChange={this.handleChange.bind(
                                        this,
                                        "address"
                                    )}
                                />
                            </Form.Item>
                        </div>

                        <div className="zen_ps-re">
                            {['14'].indexOf(this.orgId)==-1&& <span className={Uts.sc(['zen_fs-16 zen_f-left zen_ps-ab zen_t-10 zen_FF0000',this.orgId=='3'?'zen_l-33':'zen_l-20'])}>
                                *
                            </span>}
                            <Form.Item
                                label="手机号码"
                                message={mobileState.message}
                                validateStatus={mobileState.status}
                            >
                                <Input
                                    placeholder="请输入手机号码"
                                    defaultValue={info.mobile}
                                    clearable
                                    error={
                                        mobileState.status == "success"
                                            ? false
                                            : true
                                    }
                                    onChange={this.handleChange.bind(
                                        this,
                                        "mobile"
                                    )}
                                    onClearChange={this.handleChange.bind(
                                        this,
                                        "mobile"
                                    )}
                                />
                            </Form.Item>
                        </div>

                        <div className="zen_ps-re">
                            <Form.Item
                                label="固定电话"
                                message={telephoneState.message}
                                validateStatus={telephoneState.status}
                            >
                                <Input
                                    placeholder="请输入固定电话"
                                    defaultValue={info.telephone}
                                    clearable
                                    onChange={this.handleChange.bind(
                                        this,
                                        "telephone"
                                    )}
                                    onClearChange={this.handleChange.bind(
                                        this,
                                        "telephone"
                                    )}
                                />
                            </Form.Item>
                        </div>
                    </div>
                    {this.orgId == "3" && (
                        <div
                            className={Uts.sc([
                                "rj_remark",
                                selectSchool.indexOf("其他") > -1
                                    ? "rj_isRemarkReq"
                                    : ""
                            ])}
                        >
                            <Form.Item
                                label="备注"
                                message={remarkState.message}
                                validateStatus={remarkState.status}
                            >
                                <Input
                                    placeholder="校区选择其他时，必填"
                                    defaultValue={remark}
                                    clearable
                                    onChange={this.handleChange.bind(
                                        this,
                                        "remark"
                                    )}
                                    onClearChange={this.handleChange.bind(
                                        this,
                                        "remark"
                                    )}
                                />
                            </Form.Item>
                        </div>
                    )}
                    <div className="rj_l-card-btn">
                        <Button
                            onClick={this.updateDeliveryAddress.bind(
                                this,
                                info
                            )}
                        >
                            确定
                        </Button>
                        <Button onClick={this.closeModal} sub>
                            返回
                        </Button>
                    </div>
                </div>
            </div>
        );
    }
}

export default AddressItem;
